package com.nicole.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nicole.anno.CustomResult;
import com.nicole.comm.Result;
import jakarta.annotation.Resource;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author: nicole
 * @Date: 2025/06/06
 * @Description: 自定义handler实现返回统一结果实体类
 */
@RestControllerAdvice
public class GlobalResultHandler implements ResponseBodyAdvice<Object> {

    @Resource
    private ObjectMapper objectMapper;


    /**
     * 指定需要包装的方法
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !returnType.hasMethodAnnotation(CustomResult.class);
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String) {
            try {
                String value = objectMapper.writeValueAsString(Result.success(body));
                return value;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        if (body instanceof Result) {
            return body;
        }

        return Result.success(body);
    }
}
